//
//  Two22ViewController.m
//  FruitsWholesaler
//
//  Created by sgone-2 on 16/4/18.
//  Copyright © 2016年 sgone. All rights reserved.
//

#import "Two22ViewController.h"
#import "Common.h"
#import "Two22Cell.h"
#import "DataSingleton.h"
#import "AFNetworking.h"
#import "MJRefresh.h"
#import "Toast+UIView.h"
#import "LoginViewController.h"
#import "Two22DetailController.h"
#import "DDtailController.h"
@interface Two22ViewController ()<UITableViewDelegate,UITableViewDataSource>

{
    NSMutableArray *list;
    
    UIView *view20w;
    UIButton *btnw;
    UIImageView *imageVieww;
    NSString *download_url;
    Two22Cell *cell2;
    
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
//网路请求
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong)  DataSingleton *dataSingleton;

@end

@implementation Two22ViewController

static int cur_page = 1;


//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager  = [AFHTTPSessionManager manager];
    }
    return _manager;
    
    
}


//解除通知
-(void)dealloc
{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
    
}


-(void)viewWillAppear:(BOOL)animated

{


}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(creatDate) name:@"fahuo" object:nil];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.backgroundColor = BACKGROUND1;
    
    self.tableView.dataSource = self;
    
    self.tableView.delegate = self;
    
    [self creatUI];
    [self creatDate];

  
}


-(void)creatUI
{
    view20w = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, ViewHeight-48-64-46)];
    
    view20w.backgroundColor= BACKGROUND1;
    [self.view addSubview:view20w];
    
    imageVieww = [[UIImageView alloc]initWithFrame:CGRectMake((view20w.frame.size.width-80)/2, (view20w.frame.size.height-110-70)/2, 80, 110)];
    imageVieww.image = [UIImage imageNamed:@"null_default"];
    [view20w addSubview:imageVieww];
    
    
    
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(0,(view20w.frame.size.height-80-70)/2 + imageVieww.frame.size.height+10, view20w.frame.size.width, 40)];
    lbl.text = @"  还没有新的订单哦~";
    lbl.textColor = [UIColor grayColor];
    lbl.textAlignment  = NSTextAlignmentCenter;
    lbl.font = [UIFont systemFontOfSize:18];
    [view20w addSubview:lbl];
    
    
    
    btnw  = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, ViewHeight-48-64-46)];
    [btnw addTarget:self action:@selector(headerRereshing1) forControlEvents:UIControlEventTouchUpInside];
    [view20w addSubview:btnw];
    view20w.hidden = YES;
    self.tableView.hidden = NO;
    
    
}



-(void)creatDate
{
    list = [NSMutableArray arrayWithCapacity:0];
    self.dataSingleton  = [DataSingleton sharedDataSingleton];
    //进行刷新控制
    [self setupRefresh2];
   
}



#pragma mark刷新数据
- (void)setupRefresh2
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing1)];
    
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing1)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"正在帮你刷新中";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.tableView.footerRefreshingText = @"正在帮你加载中";
    
}




- (void)headerRereshing1
{
    
    //加载数据
    [self sendAPI];
    
    
}
- (void)footerRereshing1
{
    
    [self sendAPI2];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [self.tableView footerEndRefreshing];
    
}
-(void)sendAPI

{
    
    NSString *urlStr = [NSString stringWithFormat:@"%@order_summary",SERVER_ADDRESS2];
    NSDictionary *params = @{@"wTel" : self.dataSingleton.phone , @"uToken" : self.dataSingleton.uToken , @"status" : @"2" , @"cur_page" : @"1"};
    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        
        if ([responseObject[@"error_flag"] intValue] == 0)
            
            
            
        {
            if (![responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                
                [self.view makeToast:@"请检查网络"];
                return ;
            }
            else
            {
                NSArray *array = responseObject[@"data"][@"list"];
                if (array.count != 0 )
                {
                    
                    [list removeAllObjects];
                    list = [NSMutableArray arrayWithArray:array];
                    view20w.hidden = YES;
                    self.tableView.hidden = NO;
                    
                }
                else
                {
                    view20w.hidden = NO;
                    self.tableView.hidden = YES;
                }
            }
            [self.tableView reloadData];
            [self.tableView headerEndRefreshing];
            
          
        }
        else
        {
            [self.tableView headerEndRefreshing];
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            
            if ([responseObject[@"result_code"] isEqualToString:@"ERR-WHO-0005"]) {
                
                //将所有存储的数据进行清除，并且跳转到登录界面
                [self.dataSingleton removeLocalData:@"wTel"];
                LoginViewController *login = [[LoginViewController alloc]initWithNibName:nil bundle:nil];
                [self presentViewController:login animated:YES completion:nil];
                
            }
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [self.tableView headerEndRefreshing];
        view20w.hidden = NO;
        self.tableView.hidden = YES;
        [self.view makeToast:@"请检查网络"];
        
    }];
    
}
#pragma mark 进行footer的加载数据
-(void)sendAPI2
{
    
    cur_page ++;
    
    NSString *urlStr = [NSString stringWithFormat:@"%@order_summary",SERVER_ADDRESS2];
    NSDictionary *params = @{@"wTel" : self.dataSingleton.phone , @"uToken" : self.dataSingleton.uToken , @"status" : @"2" , @"cur_page" : [NSString stringWithFormat:@"%d",cur_page]};
    
    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
            if (![responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                
                [self.tableView footerEndRefreshing];
                
                return ;
            }
            else
            {
                NSArray *array = responseObject[@"data"][@"list"];
                if (array.count != 0)
                {

                    [list addObjectsFromArray:array];
                }
            }
            [self.tableView footerEndRefreshing];
            [self.tableView reloadData];
        }
        
        else
        {
            
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            
            
            if ([responseObject[@"result_code"] isEqualToString:@"ERR-WHO-0005"]) {
                
                //将所有存储的数据进行清除，并且跳转到登录界面
                [self.dataSingleton removeLocalData:@"wTel"];
                LoginViewController *login = [[LoginViewController alloc]initWithNibName:nil bundle:nil];
                [self presentViewController:login animated:YES completion:nil];
                
            }
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        [self.tableView footerEndRefreshing];
        
        [self.view makeToast:@"请检查网络"];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return    1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return list.count;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 0.01;
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 0.01;
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 28*4 /FDLaOt+ 28 /FDLaOt + 10/FDLaOt;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    cell2 = [Two22Cell cellWithTableView:tableView];
    cell2.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    if (list.count != 0) {
        
        NSDictionary *dict = list[indexPath.row];
        
        //    NSLog(@"dasdhakdhashdasdh %@",list[indexPath.row]);
        
        [cell2 loadCell:dict];
        

    }
        return cell2;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    
    Two22DetailController *DH = [[Two22DetailController alloc]initWithNibName:nil bundle:nil];
    DH.order_id = list[indexPath.row][@"order_id"];
    [DH setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:DH animated:YES];

    
    
    
}


@end
